<template>
  <div class="knowledge">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="knowledge-box">
        <div class="knowledge-left">
          <div class="left-head">
            <div class="headTitle">知识库列表</div>
            <div
              class="headSvg"
              @click="addKnowledge"
              v-show="buttonDisplayOrNot(buttonCodes, 'zskAddBtn')"
            >
              <el-icon><CirclePlus /></el-icon>
            </div>
          </div>
          <div v-if="fileTypeList.length == 0" class="noData">暂无数据</div>
          <div
            v-else
            class="left-list"
            v-for="item in fileTypeList"
            @click="getFileList(item)"
          >
            <div class="custom-tree-node show-hide">
              <ul
                :class="{
                  active: state.tableData.param.knowledgeLibraryId == item.id
                }"
              >
                {{
                  item.configValue
                }}
              </ul>
              <div class="operate">
                <a
                  style="margin-left: 8px; cursor: pointer"
                  @click.stop="editKnowledge(item)"
                  v-if="buttonDisplayOrNot(buttonCodes, 'zskEditBtn')"
                >
                  <el-icon>
                    <Edit />
                  </el-icon>
                </a>
                <el-popconfirm
                  width="150"
                  confirm-button-text="删除"
                  cancel-button-text="取消"
                  :icon="InfoFilled"
                  icon-color="#FC770A"
                  title="确定删除？"
                  @confirm="delKnowledge(item)"
                >
                  <template #reference>
                    <a
                      style="margin-left: 8px; cursor: pointer"
                      @click.stop=""
                      v-if="buttonDisplayOrNot(buttonCodes, 'zskDeleteBtn')"
                    >
                      <el-icon style="color: red"><ele-Delete /></el-icon>
                    </a>
                  </template>
                </el-popconfirm>
              </div>
            </div>
          </div>
        </div>
        <div class="knowledge-right">
          <!-- <TableSearch :search="state.search" @search="onSearch" @listenClick="listenClick" /> -->
          <el-row>
            <el-col :span="22">
              <el-input
                style="width: 30%"
                v-model="search.keyword"
                placeholder="输入文件名称搜索"
              />
              <span
                style="margin-left: 10px; font-size: var(--el-font-size-base)"
                >文件类型</span
              >
              <el-select
                v-model="search.fileType"
                class="m-2"
                placeholder="选择文件类型"
              >
                <el-option
                  v-for="item in fileType"
                  :key="item.id"
                  :label="item.configValue"
                  :value="item.id"
                />
              </el-select>
              <span
                style="margin-left: 10px; font-size: var(--el-font-size-base)"
                >设备类型</span
              >
              <a-tree-select
                v-model:value="deviceTypes"
                style="
                  margin: 5px 0;
                  width: 300px;
                  font-size: var(--el-font-size-base);
                "
                show-search
                placeholder="请选择"
                allow-clear
                multiple
                :maxTagCount="4"
                tree-default-expand-all
                :tree-data="cascaderData"
                :fieldNames="cascaderPropsAut"
                @change="cascaderChange"
              >
                <template #title="{ value: val, configValue }">
                  {{ configValue }}
                </template>
              </a-tree-select>
              <el-button
                style="margin-left: 10px"
                type="primary"
                @click="searchFor"
                >搜索</el-button
              >
              <el-button type="primary" plain @click="resetFor">重置</el-button>
            </el-col>
            <el-col :span="2" style="text-align: right">
              <el-button
                type="primary"
                @click="addFolder"
                v-if="
                  buttonDisplayOrNot(buttonCodes, 'zskAddFolderBtn') &&
                  state.tableData.param.knowledgeLibraryId != ''
                "
                >新增</el-button
              >
            </el-col>
          </el-row>
          <Table
            ref="tableRef"
            v-bind="state.tableData"
            class="table-demo"
            @pageChange="onTablePageChange"
            @listenClick="listenClick"
          >
            <template #default="{ slotData, slotColumn }">
              <div v-if="slotColumn.key === 'isSupport'">
                {{ slotData.isSupport }}
              </div>
            </template>
          </Table>
        </div>
      </div>
      <KnowledgeDialog
        :knowledgeDialog="knowledgeDialog"
        :knowledgeForm="knowledgeForm"
        @subKnow="subKnow"
        @cancelKnow="cancelKnow"
      >
      </KnowledgeDialog>
      <FolderDialog
        :folderDialog="folderDialog"
        :folderForm="folderForm"
        @cancelFolder="cancelFolder"
        @submitFolder="submitFolder"
      ></FolderDialog>
      <VersionUpdate
        :versionDialog="versionDialog"
        :versionForm="versionForm"
        @cancelVersion="cancelVersion"
        @submitVersion="submitVersion"
      >
      </VersionUpdate>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import {
  ref,
  reactive,
  defineAsyncComponent,
  getCurrentInstance,
  onMounted
} from 'vue'
import { InfoFilled, Edit, CirclePlus } from '@element-plus/icons-vue'
import {
  addDictionary,
  bindFileUrlApi,
  deleteDictionary,
  dictionaryList,
  editDictionary,
  getButtonListByRoleApi
} from '/@/api/publicApi'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  deleteDirApi,
  deleteFileApi,
  downloadDirApi,
  downloadFileApi,
  getLastVersionByDirIdApi
} from '/@/api/knowledge'
import { buttonDisplayOrNot } from '../../utils/buttonBoolean'
import { Session } from '/@/utils/storage'
const menu = Session.get('menu')
const buttonCodes = ref<any>([])
const Table = defineAsyncComponent(
  () => import('/@/components/table/index.vue')
)
const TableSearch = defineAsyncComponent(
  () => import('/@/components/table/search.vue')
)
const KnowledgeDialog = defineAsyncComponent(
  () => import('./components/KnowledgeDialog.vue')
)
const FolderDialog = defineAsyncComponent(
  () => import('./components/FolderDialog.vue')
)
const VersionUpdate = defineAsyncComponent(
  () => import('./components/VersionUpdate.vue')
)
// 页面加载时
onMounted(() => {
  menu.forEach(async (element: any) => {
    if (element.menuUrl == '/knowledge') {
      let res = await getButtonListByRoleApi({
        terminalType: 1,
        menuPid: element.id
      })
      res.data.forEach((item: any) => {
        buttonCodes.value.push(item.buttonCode)
      })
    }
  })
})
const { proxy } = getCurrentInstance() as any
// 定义变量内容
const tableRef = ref<RefType>()
const state = reactive<TableDemoState>({
  tableData: {
    flash: false, // 刷新表格
    // 表头内容（必传，注意格式）
    header: [
      { key: 'dirName', colWidth: '180', title: '文件名称', type: 'text' },
      { key: 'fileTypeName', colWidth: '120', title: '文件类型', type: 'text' },
      {
        key: 'containAmount',
        colWidth: '120',
        title: '包含版本数量',
        type: 'text'
      },
      {
        key: 'deviceTypeName',
        colWidth: '120',
        title: '设备类型',
        type: 'text'
      },
      { key: 'purpose', colWidth: '120', title: '用途', type: 'text' },
      { key: 'createUserName', colWidth: '100', title: '上传人', type: 'text' },
      { key: 'createTime', colWidth: '180', title: '上传时间', type: 'text' }
    ],
    columnBtn: [
      {
        name: 'downloadNew',
        text: '下载',
        type: 'primary',
        loading: false,
        hide(row: any): boolean {
          return true
        },
        btns: buttonCodes.value,
        btnCode: 'zskDownloadFolderBtn'
      },
      {
        name: 'editFolder',
        text: '编辑',
        color: '#1962E0',
        hide(row: any): boolean {
          return true
        },
        btns: buttonCodes.value,
        btnCode: 'zskEditFolderBtn'
      },
      {
        name: 'versionUpdate',
        text: '更新版本',
        type: 'warning',
        hide(row: any): boolean {
          return true
        },
        btns: buttonCodes.value,
        btnCode: 'zskRenewBtn'
      },
      {
        name: 'delFolder',
        text: '删除',
        type: 'danger',
        hide(row: any): boolean {
          return true
        },
        btns: buttonCodes.value,
        btnCode: 'zskDeleteFolderBtn'
      }
    ],
    // 配置项（必传）
    config: {
      listApi: '/system/mobile/sysKnowledge/knowledgeDirList',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: true, // 是否显示表格序号
      isSelection: false, // 是否显示表格多选
      isOperate: true, // 是否显示表格操作栏
      isExtend: true, // 是否可以扩展
      operateWidth: '400', //操作栏宽度
      fixed: 'right'
    },
    extendTable: {
      // 二级表格
      header: [
        { key: 'fileName', colWidth: '', title: '文件名称', type: 'text' },
        { key: 'versionNum', colWidth: '', title: '版本号', type: 'text' },
        { key: 'createUserName', colWidth: '', title: '上传人', type: 'text' },
        { key: 'createTime', colWidth: '', title: '上传时间', type: 'text' }
      ], // 第二级的头部
      dataProp: 'knowledgeList', // 第二级的数据字段
      isOperate: true, // 是否显示表格操作栏
      extendBtn: [
        {
          name: 'dwonloadFile',
          text: '下载',
          type: 'primary',
          loading: false,
          hide(row: any): boolean {
            return true
          },
          btns: buttonCodes.value,
          btnCode: 'zskDownloadFileBtn'
        },
        {
          name: 'delFile',
          text: '删除',
          hide(row: any): boolean {
            return true
          },
          type: 'danger',
          btns: buttonCodes.value,
          btnCode: 'zskDeleteFileBtn'
        }
      ]
    },
    // 搜索参数
    param: {
      knowledgeLibraryId: '' // 必传参数，分页的不要传
    }
  }
})

const search = ref({
  keyword: '',
  deviceTypes: [],
  fileType: ''
})

const cascaderData = ref([])
const cascaderPropsAut = {
  value: 'id',
  label: 'configValue',
  children: 'children'
}
const deviceTypes = ref<any>([])
const cascaderChange = (val: any) => {
  search.value.deviceTypes = val
}

const searchFor = () => {
  state.tableData.param = Object.assign({}, state.tableData.param, {
    ...search.value
  })
  state.tableData.flash = !state.tableData.flash
}

const resetFor = () => {
  search.value.keyword = ''
  search.value.deviceTypes = []
  search.value.fileType = ''
  deviceTypes.value = []
  searchFor()
}

// 初始化列表数据
const getTableData = () => {
  state.tableData.flash = !state.tableData.flash
}
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
  state.tableData.param.pageNum = page.pageNum
  state.tableData.param.pageSize = page.pageSize
  getTableData()
}

const fileTypeList = ref<any>([])
//获取知识库文件类型列表
const getKnowList = () => {
  dictionaryList({ configType: 'knowledge_library', keyword: '' }).then(
    (res) => {
      if (res.code == 0) {
        fileTypeList.value = res.data
        if (fileTypeList.value.length == 0) {
          state.tableData.param.knowledgeLibraryId = ''
          getTableData()
        } else {
          state.tableData.param.knowledgeLibraryId = fileTypeList.value[0].id
          getFileList(fileTypeList.value[0])
        }
      }
    }
  )
}
getKnowList()

const getDeviceType = () => {
  dictionaryList({ configType: 'device_type', keyword: '' }).then((res) => {
    if (res.code == 0) {
      cascaderData.value = res.data
    }
  })
}
getDeviceType()

const fileType = ref<any>([])
const getFileType = () => {
  dictionaryList({ configType: 'file_type', keyword: '' }).then((res) => {
    if (res.code == 0) {
      fileType.value = res.data
    }
  })
}
getFileType()

const getFileList = (data: any) => {
  state.tableData.param.knowledgeLibraryId = data.id
  getTableData()
}

const knowledgeDialog = ref(false)
const knowledgeForm = ref({
  title: '',
  id: '',
  val: ''
})

const addKnowledge = () => {
  knowledgeForm.value.title = '新增'
  knowledgeForm.value.id = ''
  knowledgeForm.value.val = ''
  knowledgeDialog.value = !knowledgeDialog.value
}

const editKnowledge = (val: any) => {
  knowledgeForm.value.title = '编辑'
  knowledgeForm.value.id = val.id
  knowledgeForm.value.val = val.configValue
  knowledgeDialog.value = !knowledgeDialog.value
}

const delKnowledge = async (val: any) => {
  let res = await deleteDictionary(val.id)
  if (res.code == 0) {
    ElMessage.success('删除成功！')
    getKnowList()
  }
}

const cancelKnow = () => {
  knowledgeDialog.value = !knowledgeDialog.value
}

const subKnow = (val: any) => {
  let params = {
    parentId: 0,
    configType: 'knowledge_library',
    configName: val,
    configValue: val
  }
  if (knowledgeForm.value.title == '新增') {
    addDictionary(params).then((res) => {
      if (res.code == 0) {
        ElMessage.success('新增成功')
        knowledgeDialog.value = !knowledgeDialog.value
        getKnowList()
      }
    })
  } else {
    Reflect.set(params, 'id', knowledgeForm.value.id)
    editDictionary(params).then((res) => {
      if (res.code == 0) {
        ElMessage.success('修改成功')
        knowledgeDialog.value = !knowledgeDialog.value
        getKnowList()
      }
    })
  }
}

const folderDialog = ref(false)
const folderForm = ref({
  title: '',
  id: '',
  zskId: '',
  form: {}
})
const addFolder = () => {
  folderForm.value.title = '新增'
  folderForm.value.id = ''
  folderForm.value.form = {}
  folderForm.value.zskId = state.tableData.param.knowledgeLibraryId
  folderDialog.value = !folderDialog.value
}

const editFolder = (row: any) => {
  folderForm.value.title = '编辑'
  folderForm.value.id = row.id
  folderForm.value.form = row
  folderForm.value.zskId = state.tableData.param.knowledgeLibraryId
  folderDialog.value = !folderDialog.value
}

const delFolder = (row: any) => {
  ElMessageBox.confirm('确定删除该文件夹吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteDirApi(row.id).then((res) => {
        if (res.code == 0) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          getTableData()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
const delFile = (row: any) => {
  ElMessageBox.confirm('确定删除该文件吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteFileApi(row.id).then((res) => {
        if (res.code == 0) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          getTableData()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

const cancelFolder = (val: any) => {
  folderDialog.value = !folderDialog.value
}

const submitFolder = (val: any) => {
  state.tableData.param.knowledgeLibraryId = val
  folderDialog.value = !folderDialog.value
  getTableData()
}

const versionDialog = ref(false)
const versionForm = ref({
  id: '',
  zskId: ''
})
const versionUpdate = (row: any) => {
  versionForm.value.id = row.id
  versionForm.value.zskId = state.tableData.param.knowledgeLibraryId
  versionDialog.value = !versionDialog.value
}

const cancelVersion = (val: any) => {
  versionDialog.value = !versionDialog.value
}

const submitVersion = (val: any) => {
  state.tableData.param.knowledgeLibraryId = val
  versionDialog.value = !versionDialog.value
  getTableData()
}

let timer: any = null
const dwonloadFile = async (row: any) => {
  timer && clearTimeout(timer)
  timer = setTimeout(() => {
    let a = row.fileUrl.lastIndexOf('\.')
    let str = row.fileUrl.substring(a, row.fileUrl.length)
    downloadFileApi(row.fileUrl).then(async (r: any) => {
      let blob = new Blob([r])
      let url = window.URL.createObjectURL(blob)
      const link = document.createElement('a') // 创建a标签
      link.download = row.fileName + str
      link.href = url
      console.log(url)
      link.click()
      URL.revokeObjectURL(url) // 释放内存
      state.tableData.extendTable.extendBtn[0].loading = false
    })
  }, 1000)
}

let timer2: any = null
const downloadNew = (row: any) => {
  timer2 && clearTimeout(timer2)
  timer2 = setTimeout(() => {
    downloadDirApi(row.id).then((res) => {
      if (res.code == 0) {
        ElMessage.success('下载成功,请在下载中心查看')
      } else {
      }
    })
  }, 1000)
}
//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = {
  addFolder: addFolder,
  editFolder: editFolder,
  delFolder: delFolder,
  versionUpdate: versionUpdate,
  dwonloadFile: dwonloadFile,
  delFile: delFile,
  downloadNew: downloadNew
}
// 监听子级表格  传过来的方法
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}
</script>
<style scoped lang="scss">
.knowledge {
  .knowledge-box {
    display: flex;

    .knowledge-left {
      width: 15%;
      border-right: 1px solid rgba(217, 217, 217, 1);
      padding: 4px 24px 4px 4px;

      .left-head {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;

        .headTitle {
          font-size: var(--el-font-size-base);
          font-weight: 400;
        }

        .headSvg {
          cursor: pointer;
          color: var(--el-color-primary);
          font-size: 20px;
        }
      }

      .noData {
        text-align: center;
        color: gray;
      }

      .left-list {
        display: flex;
        justify-content: space-between;
        padding: 5px;

        > ul {
          padding: 5px 0;
          font-size: 13px;
        }
      }

      .left-list:hover {
        background-color: rgba(2, 173, 130, 0.1);
        cursor: pointer;
      }
    }

    .knowledge-right {
      width: 85%;
      padding: 4px 4px 4px 24px;
    }
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: var(--el-font-size-base);
  padding-right: 8px;
}

.show-hide > div {
  display: none;
}

.show-hide:hover > div {
  display: inline-block !important;
}

.operate {
  a {
    color: var(--el-color-primary);
  }
}

.active {
  color: var(--el-color-primary);
}
</style>
